package com.duofan.gmall.cart.interceptor;

import com.duofan.gmall.cart.to.UserInfoTo;
import com.duofan.gmall.common.constant.AuthServerConstant;
import com.duofan.gmall.common.constant.CartConstant;
import com.duofan.gmall.common.constant.CommonConstant;
import com.duofan.gmall.common.vo.MemberRespVo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 执行目标方法前,判断用户登录状态,并封装传递给controller
 */
//@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        UserInfoTo to = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo vo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(vo != null) {
            // 用户没登录
            to.setUserId(vo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    to.setUserKey(cookie.getValue());
                    to.setTempUser(true);
                }
            }
        }
        if(StringUtils.isEmpty(to.getUserKey())) {
            // 如果没有临时用户,分配一个
            String uuid = UUID.randomUUID().toString();
            to.setUserKey(uuid);
        }
        threadLocal.set(to);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain(CommonConstant.DOMAIN);
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }

}
